package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.pojo.system.LoginLog;
import com.qingcheng.service.system.LoginLogService;
import com.qingcheng.util.WebUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;


public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {


    @Reference
    private LoginLogService loginLogService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //登陆成功后调用
        System.out.println("登陆成功，开始记录日志");

        String loginName = authentication.getName();//当前登录用户
        String ip = httpServletRequest.getRemoteAddr();//请求远程地址

        LoginLog loginLog = new LoginLog();

        loginLog.setLoginName(loginName);
        loginLog.setIp(ip);//远程客户端的ip
        loginLog.setLoginTime(new Date());
        loginLog.setLocation(WebUtil.getCityByIP(ip));

        String agent = httpServletRequest.getHeader("user-agent");
        loginLog.setBrowserName(WebUtil.getBrowserName(agent));

        //将获得的日志记录写入数据库并显示
        loginLogService.add(loginLog);

        //登录成功，记录日志并跳转向到main页面
        httpServletRequest.getRequestDispatcher("/main.html").forward(httpServletRequest,httpServletResponse);




    }
}
